package com.hzy.chinese.jchess.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.LogInCallback;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hzy.chinese.jchess.R;
import com.hzy.chinese.jchess.ui.activity.base.AbstractActionBarActivity;
import com.hzy.chinese.jchess.ui.dialog.DoingDialog;
import com.hzy.chinese.jchess.utils.DbUtil;
import com.hzy.chinese.jchess.utils.KeySet;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author : YYCHEN
 * e-mail : xxx@xx
 * time   : 2018/05/19
 * desc   :
 * version: 1.0
 */
public class LoginActivity extends AbstractActionBarActivity {

    private static final int REQUEST_CODE_REGISTER = 0;



    @BindView(R.id.edt_username) EditText edt_username;
    @BindView(R.id.edt_password) EditText edt_password;
    @BindView(R.id.btn_login) Button btn_login;
    @BindView(R.id.tv_register) TextView tv_register;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initView();
    }

    private void initView(){
        tv_register.setMovementMethod(LinkMovementMethod.getInstance());
        SpannableString sstr = new SpannableString(getResources().getString(R.string.action_register));
        sstr.setSpan(new ClickableSpan() {
                       @Override
                       public void onClick(View widget) {
                           //点击事件
                           LoginActivity.this.onClick(widget);
                       }
                       @Override
                       public void updateDrawState(TextPaint ds) {
                           super.updateDrawState(ds);
                           //当想要可点击文本
                           ds.setColor(getResources().getColor(R.color.link));
                           ds.setUnderlineText(false);
                       }
                   },
                0,  //可点击文本开始位置
                sstr.length(),    //可点击文本结束位置
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //标志位
        tv_register.setText(sstr);

        edt_password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(v.getId() == R.id.edt_password){
                    LoginActivity.this.onClick(btn_login);
                    return true;
                }
                return false;
            }
        });
    }

    @OnClick({R.id.btn_login})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:{
                actionLogin();
            } break;
            case R.id.tv_register:{
                String username = edt_username.getText().toString().trim();
                RegisterActivity.launchActivityForResult(this, REQUEST_CODE_REGISTER, username);
            } break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case REQUEST_CODE_REGISTER: {
                if(resultCode == RESULT_OK){
                    String username = data.getStringExtra(KeySet.Intent.KEY_USERNAME);
                    String password = data.getStringExtra(KeySet.Intent.KEY_PASSWORD);
                    edt_username.setText(username);
                    edt_password.setText(password);
                }
            } break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void actionLogin(){
        String username = edt_username.getText().toString().trim();
        String password = edt_password.getText().toString().trim();
        boolean cancel = false;
        View focusView = null;
        if (TextUtils.isEmpty(username)){
            edt_username.setError(getResources().getString(R.string.error_empty_username));
            cancel = true;
            focusView = edt_username;
        }
        if (TextUtils.isEmpty(password)){
            edt_password.setError(getResources().getString(R.string.error_empty_password), null);
            cancel = true;
            focusView = edt_password;
        }

        if(cancel){
            focusView.requestFocus();
        } else {
            loginLogic(username, password);
        }

    }

    private boolean logining = false;
    private void loginLogic(String username, String password) {
        if(logining){
            return;
        }
        logining = true;
        postShowDialog(getResources().getString(R.string.on_request_server));
        DbUtil.loginUser(username, password, new LogInCallback<AVUser>() {
            @Override
            public void done(AVUser avUser, AVException e) {
                postDismissDialog();
                logining = false;
                if(e == null){
                    finishLogin();
                }else {
                    ToastUtils.showShort(String.format(getResources().getString(R.string.login_fail), e.getMessage()));
                    LogUtils.d(e.getMessage());
                }
            }
        });
    }

    private void finishLogin() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(KeySet.Intent.KEY_GAME_CMD, KeySet.Intent.KEY_GAME_RESTART);
        startActivity(intent);
        finish();
    }


    public void postShowDialog(final String message){
        if(Looper.myLooper() == Looper.getMainLooper()){
            DoingDialog.newInstance().
                    withMessage(message)
                    .show(getSupportFragmentManager(), DoingDialog.TAG);
        }else{
            getWindow().getDecorView().post(new Runnable() {
                @Override
                public void run() {
                    postShowDialog(message);
                }
            });
        }
    }

    public void postDismissDialog(){
        if(Looper.myLooper() == Looper.getMainLooper()){
            DoingDialog.newInstance().dismiss();
        }else{
            getWindow().getDecorView().post(new Runnable() {
                @Override
                public void run() {
                    postDismissDialog();
                }
            });
        }

    }

    public static void logout(Activity activity) {
        AVUser.logOut();
        launchActivity(activity);
    }

    @Override
    protected int getlayoutResId() {
        return R.layout.activity_login;
    }


    public static void launchActivity(Activity activity){
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivity(intent);
    }



}
